import os
from datetime import datetime

from django.db.models.fields import json
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render


from facedetect.face import *
from facedetect.models import User
from facedetect.models import Class
import pandas

#导入cv模块
import cv2 as cv
class_specific = set()

def index_attendence(request):
    train_dir = r'D:\pythonProject\djangoProject2\static\img\facedetect\train'
    # 第一步，通过KNN分类器进行训练，并存储模型文件
    print("Training KNN classifier...")
    #classifier = train(train_dir, model_save_path="trained_knn_model.clf", n_neighbors=3)
    print("Training complete!")
    return render(request, "teacher_attendance.html")


def get_class(request):
    if request.method == 'POST':
        classnum = request.POST.get('classnum')#此时还是字符串
        print('从前端获取到了', classnum)
        number_of_class=classnum.count('value')
        start=0
        end=len(classnum)
        for i in range(number_of_class):
            location=classnum.find('value',start,end)
            #print(location)
            print(classnum[location+7])
            class_specific.add(classnum[location+7])
            start=location+7
        print("所有人的班级", class_specific)
        return render(request, 'teacher_attendance.html')





def upload(request):
    if request.method == 'POST':

        file = request.FILES.get('file') #获取前端上传的文件
        fix = datetime.now().strftime('%Y%m%d%H%M%S%f')+'1' #给文件加前缀防止文件名重复
		#以下用绝对路径存储文件，之前我用相对路径一直写不对
        curPath = os.path.abspath( os.path.dirname( __file__ ) )
        # InfoServiceSystem是项目名
        # 项目名称记得更换所以才可以返回图片
        rootPath = curPath[ :curPath.find("djangoProject2" ) + len( "djangoProject2" ) ]
        img_path = os.path.abspath(rootPath + '/static/img/facedetect/test/' + fix + file.name)
        #返回给前端的图片路径用相对路径，前端用绝对路径反而加载不了图片
        img_path_res = '/static/img/facedetect/result/' + fix + file.name
        img_path_test = '/static/img/facedetect/test/' + fix + file.name

        print(img_path_res)
        f = open(img_path,'wb')
        for i in file.chunks():
            f.write(i)
        f.close()

        var=face_detect1(img_path_test,img_path_res)
        var1=len(var)

        path='media/face_detect.xlsx'
        writer = pandas.ExcelWriter(path)
        sheet_name1='chuqin'
        #获得出勤名单
        stu={"name":[],
             'sid':[],
             'college':[],
             'class_field':[]}
        for name in var:
            user_obj=User.objects\
                .values("uid","name","sid","college","class_field")\
                .filter(name=name)

            stu['name'].append(user_obj[0]['name'])
            stu['sid'].append(user_obj[0]['sid'])
            stu['college'].append(user_obj[0]['college'])
            stu['class_field'].append(user_obj[0]['class_field'])
        print("下面打印stu", stu)
        df = pandas.DataFrame(stu)
        df.to_excel(
                excel_writer=writer,
                sheet_name=sheet_name1,
                index=False)


        sheet_name2='queqin'
        #获得缺勤名单
        #先获得同伴的所有人
        stu2={"name":[],
             'sid':[],
             'college':[],
             'class_field':[]}
        for class1 in class_specific:
            user_obj2=User.objects\
                .values("uid","name","sid","college","class_field")\
                .filter(class_field=class1)
            user_obj2=list(user_obj2)
            #在此减去那些同一个班但是来上课的人
            for name in var:
                user_obj3 = User.objects \
                    .values("uid", "name", "sid", "college", "class_field") \
                    .filter(name=name)
                user_obj3 = list(user_obj3)
                for j in user_obj3:
                    if j in user_obj2:
                        user_obj2.remove(j)
            for i in user_obj2:
                stu2['name'].append(i['name'])
                stu2['sid'].append(i['sid'])
                stu2['college'].append(i['college'])
                stu2['class_field'].append(i['class_field'])
        print("下面打印stu2", stu2)
        df2 = pandas.DataFrame(stu2)
        df2.to_excel(
                excel_writer=writer,
                sheet_name=sheet_name2,
                index=False)
        writer.save()


        #return JsonResponse({'img_name': img_path_res, 'code': var})
        # return render(request, "teacher_attendance.html", {'numberofAttence': var})
        return JsonResponse({
            "status":0,
            'img_path': img_path_res,
            'total':var1,
            "data": stu
        })









#检测图像
# def face_detect_demo(img):
#     # print("进入了face_detect_demo函数")
#     # print(img)
#     gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#     # print("下面打印gray")
#     # print(gray)
#     #加载分类器,调用opeccv自带的haar分类器，没有自己训练（自己训练还涉及到机器学习和深度学习了，目前只是简单实现）
#     #这里的路径目前是绝对路径，相对路径会报错
#     face_detect = cv.CascadeClassifier(r'D:\pythonProject\djangoProject\facedetect\haarcascade_frontalface_default.xml')
#     # face_detect = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
#     # print("下面打印face_detect")
#     # print(face_detect)
#     face=face_detect.detectMultiScale(gray)
#     # print("下面打印face")
#     # print(face)
#     for x,y,w,h in face:
#         cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
#     #cv.imshow('result',img)
#     #if len(face):
#         #print("现场有{0}个人".format(len(face)))
#     #else:
#         #print("没有人")
#     # print("下面打印len(face)")
#     # print(len(face))
#     return (len(face))
